<?php

/**
 * 重庆双击科技 JDK
 * @author chenshubo
 */
namespace App\Service\VendorClient\ShopcqsjApi;
use App\Service\Code\Normal;
use App\Service\OrderService\BaseSupplierRouterService;

class ShopcqsjApiClient extends BaseSupplierRouterService
{
    private $app_key;
    private $app_id;
    private $version;
    private $order_url;
    private $express_url;
    private $clientConfig;
    private $config = [];
    public function __construct($apiBody = [])
    {
        $this->clientConfig = $apiBody;
        print_r($this->clientConfig);die;
        $this->app_id       = $this->clientConfig['app_id'];
        $this->app_key      = $this->clientConfig['app_key'];
        $this->version      = $this->clientConfig['version'];
        $this->order_url    = $this->clientConfig['acount']['APPLY_ORDER_URL'];
        $this->express_url  = $this->clientConfig['acount']['APPLY_EXPRESS_URL'];
    }

    /**
     * 查询物流信息
     * @param array $params
     */
    public function queryOrder( $params = []) {

        if( empty($params['order_sn']) ) {
            return Normal::returnCode(Normal::FAIL,"order_sn 参数不能为空");
        }

        $param = [
            'app_id'   => $this->app_id,
            'version'  => $this->version,
            'order_sn' => json_encode($params['order_sn']),
        ];

        $param = $this->getSignParam($param);
        return $this->execute([
            'method'    => 'queryOrder',
            'data'      => $param
        ]);
    }

    /**
     * 提交并支付订单
     */
    public function createOrder( $param = [] )
    {
        $orderInfo      = $param['supplierOrder'];
        $goodsList      = $param['orderGoods'];
        $order          = $param['order'];
        $binfo          = $param['binfo'];
        $pay_sn         = $order['paySerial']??$orderInfo['pay_sn'];
        $orderGoods     = current($goodsList);
        $price          = $orderGoods['price'];

        //税费 = 商品售价 * 税率
        $tax_rate_all   = bcadd((string)$orderGoods['tax_rate'],'1.0000',4);

        //商品不含税价格
        $actual_price   = bcdiv((string)$price, (string)$tax_rate_all,2);

        $quantity       = $orderGoods['quantity'];
        $spec_num       = $orderGoods['spec_num'];
        $spec_name      = $orderGoods['spec_name'];

        //判断下单数量是不是大于1
        if( $quantity > 1 ) {
            return Normal::returnCode(Normal::FAIL,"当前商品不支持多个多件套装购买[100011]");
        }

        //单件装的价格
        $singleGoodsPrice = bcdiv((string)$actual_price, (string)$spec_num,2);

        //销售成本单价
        $singleGoodsCostPrice = bcdiv((string)$orderGoods['costprice'],(string)$spec_num,2);

        $palceOrderGoods = [
            'supplies_sn'       => $orderGoods['supplier_skucode'],
            'goods_name'        => $orderGoods['goods_name'],
            'term'              => $orderGoods['batch_no']. '/'.$orderGoods['batch_no'] , // 有效期
            'goods_attr_number' => $spec_num,   // 规格数量
            'goods_attr_name'   => $spec_name,  // 规格名称
            'goods_price'       => $singleGoodsPrice,
            'goods_costprice'   => $singleGoodsCostPrice,
        ];

        //商品金额
        $productAmt     = bcmul((string)$spec_num, (string)$singleGoodsPrice,2);

        //运费
        $deliver_money  = $orderInfo['deliver_money'];

        //税费
        $tax_amount     = bcsub((string)$price, (string)$productAmt,2);

        //订单总金额计算 = 向海关申报的商品货款总额 + 向海关申报的运费金额 + 向海关申报的订单跨境综合税总的税金
        $ActualPaidAmt  = bcadd((string)$productAmt, (string)$deliver_money,2);
        $ActualPaidAmt  = bcadd((string)$ActualPaidAmt, (string)$tax_amount,2);

        $time = time();
        $data = [
            'app_id'       =>   $this->app_id,
            'version'      =>   $this->version,
            'order_sn'     =>   $orderInfo['supplier_dsn'],
            'add_time'     =>   $time,
            'pay_id'       =>   2, // 6 -支付宝  5 -微信  3 -网银   2 -其他
            'order_type'   =>   1, //保税商品
            'consignee'    =>   $orderInfo['buyer_realname'], // 收货人姓名
            'tel'          =>   $orderInfo['buyer_phone'], // 收货人手机号
            'nric'         =>   $orderInfo['buyer_idcard'],
            'province'     =>   $orderInfo['province'],
            'city'         =>   $orderInfo['city'],
            'district'     =>   $orderInfo['district'],
            'address'      =>   $orderInfo['receive_address'],
            'goods_amount' =>   $productAmt,
            'shipping_fee' =>   $deliver_money,
            'tax_amount'   =>   $tax_amount,
            'order_amount' =>   (float)$ActualPaidAmt,
            'pay_sn'       =>   $pay_sn,
            'pay_time'     =>   $time,
            'dg_name'      =>   $orderInfo['buyer_realname'],
            'dg_phone'     =>   $orderInfo['buyer_phone'],
            'dg_card'      =>   $orderInfo['buyer_idcard'],
            'goods_data'   =>   json_encode($palceOrderGoods),
        ];

        $data = $this->getSignParam($data);
        return $this->execute([
            'method'    => 'createOrder',
            'data'      => $data
        ]);
    }

    /**
     * 组装签名
     */
    private function getSignParam( $param = [] ) {
        ksort($param);
        $signData=array_values($param);
        $signData=join('',$signData);
        $sign=md5(base64_encode($signData.$this->app_key));
        $param['sign']=$sign;
        return $param;
    }

    /**
     * CURL请求
     * @param $params
     * @return mixed
     */
    public function execute( $param = [] )
    {
        $start_time = microtime(true);

        if( $param['method'] == 'createOrder' ) {
            $url        = $this->order_url;
            $header = [
                "Content-Type: Accept:application/form-data",
                "Accept:application/json"
            ];
            return Normal::returnCode(Normal::SUC,"获取成功",[
                'url'       => $url,
                'data'      => $param['data'],
                'format'    => 'form-data'
            ]);
        } elseif($param['method']=='queryOrder') {
            $url = $this->express_url;
            $res = Http::apiRequest($url,$param['data'],'post',[
                "Content-Type: application/x-www-form-urlencoded"
            ]);
            $resHttp = json_decode($res,true);
        }

        QueryGoodsMicService::instance()->addRequestLog([
            'interface_code'    => 'cqsj_'.$param['method'],
            'request_url'       => $url,
            'request_param'     => $param['data'],
            'response_code'     => $resHttp['code'],
            'response_data'     => $res,
            'start_time'        => $start_time,
        ]);

        if( isset($resHttp['code']) && $resHttp['code'] == '0000' ) {
            return Normal::returnCode(Normal::SUC,"获取成功");
        }

        $message = isset($resHttp['msg']) ? $resHttp['msg'] : '操作失败';
        return Normal::returnCode(Normal::FAIL,$message,$resHttp['data']??[]);
    }

    /**
     * 查询物流信息
     * @param array $params
     */
    public function queryOrderExpress( $params = []) {

        if( empty($params['supplier_dsn']) ) {
            return Normal::returnCode(Normal::FAIL,"supplier_dsn 参数不能为空");
        }

        $param = [
            'app_id'   => $this->app_id,
            'version'  => $this->version,
            'order_sn' => json_encode( [$params['supplier_dsn']]),
        ];

        $param = $this->getSignParam($param);
        return $this->execute([
            'method'    => 'queryOrder',
            'data'      => $param
        ]);
    }

}
